<script setup lang="ts">
import { ref, watch, onMounted, reactive } from "vue";
import { useLink } from "./useLink";
import { NButton } from "naive-ui";
import { NInput, NPopselect, NAlert, NIcon, NProgress } from "naive-ui";
import { useMessage } from "naive-ui";
import { Close } from "@vicons/ionicons5";
import jButtons from "./j-buttons/index.vue";
import axios from "axios";

const message = useMessage();
const percentage = ref(0);
const loading = ref(false);
const content = ref<HTMLElement>(null as any);
const ids = [
    { label: "1", value: 1 },
    { label: "2", value: 2 },
    { label: "3", value: 3 }
];
const btnObj = reactive({
    list: ids,
    curItem: ids[2]
});

const { list, send, close, clear, connect, addItem } = useLink(toButtom);
const fs = ref();

onMounted(() => {
    update();
});


const update = () => {
    axios
        .get("/app/temp")
        .then(res => {
            console.log(res);
            clear();
            res.data.data.forEach((element: any) => {
                if (element.type == "image") {
                    addItem(element._id, element.hash, true);
                } else {
                    addItem(element._id, JSON.stringify(element));
                }
            });
            // toButtom();
        })
        .catch(error => {
            console.error(error);
        });
};

function toButtom(){
    setTimeout(() => {
        console.log(content.value.scrollTop, content.value.scrollHeight, "000")
        content.value.scrollTop = content.value.scrollHeight;
    }, 900);
}

const onSend = () => {
    let suc = send(msg.value);
    if (suc) {
        msg.value = "";
    } else {
        axios
            .post("/app/temp", {
                msg: msg.value
            })
            .then((response: any) => {
                update();
                console.log(response);
                toButtom();
            })
            .catch(error => {
                console.error(error);
                message.warning("发送失败");
            });
    }
};

const onConnect = () => {
    connect(address.value);
    localStorage.setItem("address", address.value);
};

const onClose = () => {
    close();
};

const onClear = () => {
    clear();
};

const onUpload = () => {
    fs.value.click();
};
const onFile = (e: any) => {
    console.log(e);
    loading.value = true;
    const formData = new FormData();
    formData.append("files", e.target.files[0], "files");
    formData.append("type", "image");
    axios
        .post("/app/temp/upload", formData, {
            headers: {
                "Content-Type": "multipart/form-data"
            },
            onUploadProgress: function (progressEvent: any) {
                percentage.value = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                console.log(`上传进度： ${percentage.value}%`);
            }
        })
        .then(response => {
            console.log(response);
            update();
        })
        .catch(error => {
            console.error(error);
            message.warning("上传失败");
        })
        .finally(() => {
            loading.value = false;
        });
};

const onRemove = (item: any) => {
    console.log(item);
    axios
        .delete("/app/temp/" + item.id)
        .then(response => {
            console.log(response.data);
            update();
        })
        .catch(error => {
            console.error(error);
            message.warning("删除失败");
        });
};

const msg = ref("");
const address = ref(localStorage.getItem("address") || "");
const server = ref(null);
const options = ref([
    {
        label: "ws://120.48.63.39/ws",
        value: "ws://120.48.63.39/ws"
    },
    {
        label: "ws://120.48.63.39:8989/ws",
        value: "ws://120.48.63.39:8989/ws"
    },
    {
        label: "wss://www.step2step.cn/ws",
        value: "wss://www.step2step.cn/ws"
    },
    {
        label: "wss://www.step2step.cn:8989/ws",
        value: "wss://www.step2step.cn:8989/ws"
    }
]);

watch(
    () => server.value,
    val => {
        address.value = val + "";
    }
);
</script>

<template>
    <div class="page">
        <div class="header">
            <n-input class="txt" v-model:value="address" placeholder="请输入连接地址" clearable />

            <div class="group">
                <n-popselect v-model:value="server" :options="options" trigger="click">
                    <n-button ghost>默认服务器</n-button>
                </n-popselect>
                <n-button @click="onConnect" ghost type="primary">连接服务</n-button>
                <n-button @click="onClear" ghost type="warning">清空</n-button>
                <n-button @click="onClose" ghost type="error">断开连接</n-button>
                <n-button @click="onUpload" ghost type="primary">上传</n-button>
                <!-- <jButtons :list="btnObj.list" v-model="btnObj.curItem"></jButtons> -->
            </div>
        </div>
        <div class="content" ref="content">
            <div v-for="item in list" class="items" :key="item.id">
                <n-alert v-if="item.img" :title="item.title" :type="item.type" :show-icon="item.type !== 'default'">
                    <div class="img-box">
                        <img class="img" :src="'/asset/temp/' + item.img" />
                    </div>
                </n-alert>

                <n-alert v-else :title="item.title" :type="item.type" :show-icon="item.type !== 'default'">
                    {{ item.msg }}
                </n-alert>
                <div class="close" @click="onRemove(item)" v-if="item.id">
                    <n-icon size="20" :component="Close"></n-icon>
                </div>
            </div>
        </div>

        <div class="footer">
            <n-input class="txt" v-model:value="msg" type="textarea" />
            <div class="btns">
                <n-button @click="onSend" type="primary">发送</n-button>
                <n-button @click="msg = ''" type="warning">清除</n-button>
            </div>
        </div>
        <input type="file" style="display: none" @change="onFile" ref="fs" />
        <div class="loading" v-show="loading">
            <n-progress type="circle" :percentage="percentage" />
        </div>
    </div>
</template>

<style scoped>
.page {
    display: flex;
    flex-direction: column;
    width: 100vw;
    height: 100%;
}

.header {
    padding: 10px;
    position: relative;
    z-index: 1;
    box-shadow: 0px 2px 20px rgb(143, 143, 143, 0.3);
}

.content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 10px;
    height: 0;
    overflow-y: auto;
    padding: 10px;
    box-sizing: border-box;
    background: #eee;
    scroll-behavior: smooth;
}

.footer {
    background: #fff;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    padding: 10px;
    box-sizing: border-box;
    box-shadow: 0px -2px 20px rgb(143, 143, 143, 0.3);
    position: relative;
    z-index: 1;
}

.txt {
    flex: 1;
}

.btns {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.group {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 10px 0;
}

.card {
    margin-bottom: 10px;
}

.img-box {
    width: 100%;
}

.img {
    max-width: 100%;
}

.items {
    position: relative;
}

.close {
    position: absolute;
    top: 6px;
    right: 6px;
    z-index: 1;
    color: #ff0000;
    cursor: pointer;
}

.loading {
    position: fixed;
    z-index: 3;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.32);
}</style>
